<?php
/**
 * 文章发布页面文件
 * 这个页面用于创建和发布新的博客文章
 * 包含文章标题、内容、分类、标签、图片上传等功能
 * 只有登录用户才能访问这个页面
 */

// 引入系统初始化文件，包含所有必要的类和函数
require_once '../includes/init.php';

// 调试模式已在BlogSystem类中默认关闭，可以在类中开启用于调试

// 检查用户是否已经登录，未登录用户无法发布文章
if (!$blog->isLoggedIn()) {
    // 跳转到登录页面
    redirect('../login.php');
}

// 获取当前登录用户的完整信息
$currentUser = $blog->getCurrentUser();

// 从数据库获取所有可用的分类列表，用于下拉选择
$categories = $blog->getCategories();
// 从数据库获取所有可用的标签列表，用于下拉选择
$tags = $blog->getTags();

// 初始化消息变量，用于显示操作结果
$message = '';      // 消息内容
$messageType = '';  // 消息类型（success/error/info）

// 处理文章发布请求
// isPost()检查是否为POST请求，getPost()获取POST数据并验证
if (isPost() && !empty(getPost('title')) && !empty(getPost('content'))) {
    
    // 验证CSRF令牌，防止跨站请求伪造攻击
    // verifyCSRFToken()函数会比较表单提交的令牌和session中的令牌
    if (!verifyCSRFToken(getPost('csrf_token'))) {
        // CSRF验证失败，显示详细错误信息用于调试
        $message = 'CSRF验证失败，请重新提交。提交令牌：' . getPost('csrf_token') . '，Session令牌：' . (isset($_SESSION['csrf_token']) ? $_SESSION['csrf_token'] : '未设置');
        $messageType = 'error';
    } else {
        // CSRF验证通过，开始处理文章数据
        
        // 获取表单提交的基本数据
        $title = getPost('title');           // 文章标题
        $content = getPost('content');       // 文章内容
        
        // 处理复选框数据，如果选中返回1，否则返回0
        $isTop = isset($_POST['is_top']) ? 1 : 0;           // 是否置顶
        $isRecommend = isset($_POST['is_recommend']) ? 1 : 0; // 是否推荐
        
        // 获取选中的分类和标签，如果没有选择则返回空数组
        $selectedCategories = getPost('categories', []);
        $selectedTags = getPost('tags', []);
        
        // 处理图片上传功能
        $imagePath = '';  // 初始化图片路径
        
        // 检查是否有文件上传且没有上传错误
        if (isset($_FILES['article_image']) && $_FILES['article_image']['error'] !== UPLOAD_ERR_NO_FILE) {
            // 使用BlogSystem类的uploadImage方法处理图片上传
            $uploadResult = $blog->uploadImage($_FILES['article_image']);
            
            // 检查上传是否成功
            if ($uploadResult['success']) {
                // 上传成功，保存图片路径
                $imagePath = $uploadResult['path'];
            } else {
                // 上传失败，设置错误消息
                $message = '图片上传失败：' . $uploadResult['error'];
                $messageType = 'error';
            }
        }
        
        // 验证必填字段是否为空
        if (empty($title) || empty($content)) {
            $message = '请填写文章标题和内容';
            $messageType = 'error';
        } elseif (!$message) { 
            // 只有在没有上传错误时才继续发布文章
            
            // 准备要保存到数据库的文章数据数组
            $articleData = [
                'title' => $title,                    // 文章标题
                'content' => $content,                // 文章内容
                'user_id' => $currentUser['id'],      // 作者ID
                'is_top' => $isTop,                   // 是否置顶
                'is_recommend' => $isRecommend,       // 是否推荐
                'image' => $imagePath,                // 文章图片路径
                'categories' => $selectedCategories,  // 选中的分类
                'tags' => $selectedTags              // 选中的标签
            ];
            
            // 调用BlogSystem类的publishArticle方法发布文章
            // 返回新创建文章的ID，失败返回false
            $articleId = $blog->publishArticle($articleData);
            
            // 检查文章是否发布成功
            if ($articleId) {
                // 发布成功，设置成功消息
                $message = '文章发布成功！';
                $messageType = 'success';
                
                // 发布成功后自动跳转到新文章的详情页面
                redirect("../article.php?id=$articleId");
            } else {
                // 发布失败，设置错误消息
                $message = '文章发布失败，请稍后重试';
                $messageType = 'error';
            }
        }
    } // 关闭CSRF验证的else代码块
}

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布文章 - 管理后台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            line-height: 1.6;
        }

        .admin-header {
            background: white;
            color: #333;
            padding: 20px 0;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            border-radius: 15px;
            margin-bottom: 30px;
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 20px;
            font-weight: bold;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .nav-links {
            display: flex;
            gap: 15px;
        }

        .nav-links a {
            color: #333;
            text-decoration: none;
            padding: 8px 15px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .nav-links a:hover {
            background-color: #3498db;
            color: white;
        }

        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .page-header {
            background: white;
            padding: 30px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 15px 50px rgba(0,0,0,0.2);
            position: relative;
            overflow: hidden;
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .page-title {
            font-size: 28px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .page-description {
            color: #666;
            font-size: 16px;
        }

        .form-container {
            background: white;
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 15px 50px rgba(0,0,0,0.2);
            position: relative;
            overflow: hidden;
        }

        .form-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-control {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-2px);
        }

        textarea.form-control {
            height: 300px;
            resize: vertical;
        }

        .checkbox-group {
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            padding: 20px;
            background: #f8f9fa;
            transition: all 0.3s ease;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 10px;
        }

        .checkbox-group:hover {
            border-color: #667eea;
            background: white;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: background-color 0.3s;
            cursor: pointer;
        }

        .checkbox-item:hover {
            background-color: rgba(102, 126, 234, 0.1);
        }

        .checkbox-item input[type="checkbox"] {
            width: 18px;
            height: 18px;
        }

        .multi-select {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            padding: 20px;
            background: #f8f9fa;
            transition: all 0.3s ease;
            min-height: 150px;
            max-height: 200px;
            overflow-y: auto;
        }

        .multi-select:hover {
            border-color: #667eea;
            background: white;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
                gap: 20px;
            }
        }

        .multi-select label {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 0;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: background-color 0.3s;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .multi-select label:hover {
            background-color: rgba(102, 126, 234, 0.1);
        }

        .multi-select input[type="checkbox"] {
            width: 16px;
            height: 16px;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: #95a5a6;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-start;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e1e1e1;
        }

        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 25px;
            text-align: center;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .file-upload {
            position: relative;
            display: inline-block;
            cursor: pointer;
            width: 100%;
        }

        .file-upload input[type="file"] {
            position: absolute;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-upload-label {
            display: block;
            padding: 20px;
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            text-align: center;
            transition: all 0.3s ease;
            background: #f8f9fa;
            cursor: pointer;
        }

        .file-upload:hover .file-upload-label {
            border-color: #667eea;
            background: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
        }

        .help-text {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        .image-preview {
            margin-top: 10px;
        }

        .image-preview img {
            max-width: 300px;
            max-height: 200px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .remove-image {
            display: inline-block;
            margin-top: 10px;
            color: #e74c3c;
            cursor: pointer;
            font-size: 14px;
        }

        .remove-image:hover {
            text-decoration: underline;
        }

        .multi-select {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 10px;
        }

        .multi-select label {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: normal;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <header class="admin-header">
        <div class="header-content">
            <div class="logo">博客管理后台</div>
            <div class="user-info">
                <span>欢迎，<?php echo escape($currentUser['用户名']); ?></span>
                <nav class="nav-links">
                    <a href="index.php">后台首页</a>
                    <a href="articles.php">文章管理</a>
                    <a href="../index.php">前台首页</a>
                    <a href="../logout.php">退出登录</a>
                </nav>
            </div>
        </div>
    </header>

    <div class="container">
        <div class="page-header">
            <h1 class="page-title">发布新文章</h1>
            <p class="page-description">在这里发布您的新文章，分享您的想法和知识</p>
        </div>

        <div class="form-container">
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?>">
                    <?php echo escape($message); ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <?php csrfField(); ?>
                
                <div class="form-group">
                    <label for="title">文章标题 *</label>
                    <input type="text" id="title" name="title" class="form-control" 
                           placeholder="请输入文章标题" required>
                </div>

                <div class="form-group">
                    <label for="content">文章内容 *</label>
                    <textarea id="content" name="content" class="form-control" 
                              placeholder="请输入文章内容..." required></textarea>
                </div>

                <div class="form-group">
                    <label for="article_image">文章配图</label>
                    <div class="file-upload">
                        <input type="file" id="article_image" name="article_image" accept="image/*">
                        <label for="article_image" class="file-upload-label" id="file-label">
                            点击选择图片或拖拽图片到此处
                        </label>
                    </div>
                    <div class="help-text">支持JPG、PNG、GIF格式，大小不超过2MB</div>
                    <div id="image-preview" class="image-preview"></div>
                </div>

                <?php if (!empty($categories) || !empty($tags)): ?>
                <div class="form-row">
                    <?php if (!empty($categories)): ?>
                    <div class="form-group">
                        <label>选择分类</label>
                        <div class="multi-select">
                            <?php foreach ($categories as $category): ?>
                                <label>
                                    <input type="checkbox" name="categories[]" value="<?php echo $category['id']; ?>">
                                    <?php echo escape($category['分类名']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <div class="help-text">可以选择多个分类</div>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($tags)): ?>
                    <div class="form-group">
                        <label>选择标签</label>
                        <div class="multi-select">
                            <?php foreach ($tags as $tag): ?>
                                <label>
                                    <input type="checkbox" name="tags[]" value="<?php echo $tag['id']; ?>">
                                    <?php echo escape($tag['标签名']); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <div class="help-text">可以选择多个标签</div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <div class="form-group">
                    <label>文章设置</label>
                    <div class="checkbox-group">
                        <div class="checkbox-item">
                            <input type="checkbox" id="is_top" name="is_top">
                            <label for="is_top">置顶文章</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="is_recommend" name="is_recommend">
                            <label for="is_recommend">推荐文章</label>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" name="submit_post" class="btn">发布文章</button>
                    <a href="index.php" class="btn btn-secondary">返回后台</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 图片上传预览功能
        document.getElementById('article_image').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('image-preview');
            const label = document.getElementById('file-label');
            
            if (file) {
                // 验证文件类型
                if (!file.type.match('image.*')) {
                    alert('请选择图片文件！');
                    this.value = '';
                    return;
                }
                
                // 验证文件大小（2MB）
                if (file.size > 2 * 1024 * 1024) {
                    alert('图片文件不能超过2MB！');
                    this.value = '';
                    return;
                }
                
                // 更新标签文本
                label.textContent = '已选择：' + file.name;
                label.style.color = '#27ae60';
                label.style.borderColor = '#27ae60';
                
                // 创建图片预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `
                        <img src="${e.target.result}" alt="图片预览">
                        <br>
                        <span class="remove-image" onclick="removeImage()">× 移除图片</span>
                    `;
                };
                reader.readAsDataURL(file);
            } else {
                // 重置状态
                label.textContent = '点击选择图片或拖拽图片到此处';
                label.style.color = '';
                label.style.borderColor = '';
                preview.innerHTML = '';
            }
        });
        
        // 移除图片功能
        function removeImage() {
            const input = document.getElementById('article_image');
            const preview = document.getElementById('image-preview');
            const label = document.getElementById('file-label');
            
            input.value = '';
            preview.innerHTML = '';
            label.textContent = '点击选择图片或拖拽图片到此处';
            label.style.color = '';
            label.style.borderColor = '';
        }
        
        // 表单提交前验证
        document.querySelector('form').addEventListener('submit', function(e) {
            const title = document.getElementById('title').value.trim();
            const content = document.getElementById('content').value.trim();
            
            if (!title) {
                alert('请输入文章标题！');
                document.getElementById('title').focus();
                e.preventDefault();
                return false;
            }
            
            if (!content) {
                alert('请输入文章内容！');
                document.getElementById('content').focus();
                e.preventDefault();
                return false;
            }
            
            // 显示提交状态
            const submitBtn = document.querySelector('button[name="submit_post"]');
            submitBtn.textContent = '发布中...';
            submitBtn.disabled = true;
            
            return true;
        });
        
        // 拖拽上传功能
        const fileUpload = document.querySelector('.file-upload');
        
        fileUpload.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.backgroundColor = '#f0f8ff';
            this.querySelector('.file-upload-label').style.borderColor = '#3498db';
        });
        
        fileUpload.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.backgroundColor = '';
            this.querySelector('.file-upload-label').style.borderColor = '';
        });
        
        fileUpload.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.backgroundColor = '';
            this.querySelector('.file-upload-label').style.borderColor = '';
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                document.getElementById('article_image').files = files;
                // 触发change事件
                document.getElementById('article_image').dispatchEvent(new Event('change'));
            }
        });
    </script>
</body>
</html> 